﻿#include "ssThreadPool.h"


namespace StarSeeker
{
	int ssThreadPool::s_weight[32] = {
		-1,-1,-1,-1,0,0,0,0,
		1,1,1,1,1,1,1,1,
		2,2,2,2,2,2,2,2,
		3,3,3,3,3,3,3,3
	};

	ssThreadPool::ssThreadPool()
	{
		m_condGet.BindLock(&m_mutex);
	}

	ssThreadPool::~ssThreadPool()
	{
		Exit();
	}

	void ssThreadPool::Start()
	{
		for (size_t i = 0; i < m_threads.size(); ++i)
		{
			m_threads[i]->m_threadId = i;
			m_threads[i]->m_weight = i < 32 ? ssThreadPool::s_weight[i] : 0;
			m_threads[i]->StartThread();
		}
	}

	void ssThreadPool::Exit()
	{
		for (size_t i = 0; i < m_threads.size(); ++i)
		{
			m_threads[i]->RequestStop();
		}
		m_condGet.NotifyAll();
		for (size_t i = 0; i < m_threads.size(); ++i)
		{
			delete m_threads[i];
		}
		m_threads.clear();
	}

	void ssThreadPool::PostMsg(ssMsg_s &m)
	{
		SS_MUTEX_LOCK(m_mutex) //锁定互斥量
			m_msgList.PushBack(m);
			m_condGet.NotifyOne(); //通知可以读取数据
		SS_MUTEX_UNLOCK(m_mutex)
	}

	void ssThreadPool::PostMsg(u32 msgID, u32 subID, ulint param1, ulint param2, ulint param3)
	{
		ssMsg_s m;
		m.msgID = msgID;
		m.subID = subID;
		m.param[0] = param1;
		m.param[1] = param2;
		m.param[2] = param3;
		PostMsg(m);
	}

	void ssThreadPool::AddThread(ssWorkThread* pThread)
	{
		if (m_threads.size() < 256)
		{
			m_threads.push_back(pThread);
		}
	}

	void ssThreadPool::AddThreads(ssWorkThread* pThreadArr[], u32 count)
	{
		if (m_threads.size()==0 && count < 256)
		{
			for (u32 i = 0; i < count; i++)
			{
				m_threads.push_back(pThreadArr[i]);
			}
		}
	}

}
